﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using ZLDC.Common.Estate;

namespace ZLDC.Common.BaseUser
{
    public class UserInfo
    {
        public static void GetInfo(string UserID, ref Param m_Param)
        {
            DataSet ds = new DataSet();
            string sSql;
            sSql = "select t_id,name,r_id,status,tel,(select name from org_unit where  ID in(select unitID from t_zldc_deptinfo where id=t_id)) as tname,(select hrms_userField_51 from  org_departmentattch where  unitID  = (select unitID from t_zldc_deptinfo where id=t_id)) as fhname,mail,email,fgs, station,[no] from t_s_allusr where id = " + UserID;
            ds.Tables.Clear();
            DataBaseAll db = new DataBaseAll("ZLDCHR");
            ds = db.SelectDataBaseAll(sSql);
            m_Param.m_sUserID = UserID;
            m_Param.m_sEHRUserID = UserID;
            m_Param.m_sUserName = ds.Tables[0].Rows[0]["name"].ToString();
            m_Param.m_sStatus = ds.Tables[0].Rows[0]["status"].ToString(); m_Param.m_sTel = ds.Tables[0].Rows[0]["tel"].ToString(); m_Param.m_sDeptID = ds.Tables[0].Rows[0]["t_id"].ToString();
            if (m_Param.m_sDeptID == "805")
            {
                m_Param.m_sDeptID = "4481";
            }
            m_Param.m_sDeptName = ds.Tables[0].Rows[0]["tname"].ToString();

            m_Param.m_sRoleID = ds.Tables[0].Rows[0]["r_id"].ToString();

            m_Param.m_sMail = ds.Tables[0].Rows[0]["mail"].ToString();
            m_Param.m_sEmail = ds.Tables[0].Rows[0]["email"].ToString();
            m_Param.m_sFgs = ds.Tables[0].Rows[0]["fgs"].ToString();
            m_Param.m_sStation = ds.Tables[0].Rows[0]["station"].ToString();
            m_Param.m_sNo = ds.Tables[0].Rows[0]["no"].ToString();
            m_Param.m_fhName = ds.Tables[0].Rows[0]["fhname"].ToString();
            m_Param.m_dsPdm = new DataSet();

            m_Param.m_sDlIdList = "";

            m_Param.m_sChildrenDeptList = getAllChildDept(m_Param.m_sDeptID, UserID);
        }

        #region

        public static bool GetPopedom(DataSet dsPdm, string sPdmList, string pdm)
        {
            if (string.IsNullOrEmpty(sPdmList)) return false;
            for (int i = 0; i < dsPdm.Tables[0].Rows.Count; i++)
            {
                if (dsPdm.Tables[0].Rows[i]["pdm"].ToString() == pdm)
                {
                    int n = Convert.ToInt32(dsPdm.Tables[0].Rows[i]["pdmpos"].ToString()) - 1;
                    if (sPdmList[n] == '1')
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            return false;
        }

        public static bool GetPopedom(string pdm)
        {
            Param param = (Param)System.Web.HttpContext.Current.Session["info"];
            DataTable dt = new DataTable();

            string cachekey = "rolelist_" + param.m_sRoleID; int cachetime = 3600 * 12;
            dt = (DataTable)ZLDC.Common.Estate._Cache.GetCache(cachekey);

            if (dt == null || dt.Rows.Count <= 0)
            {
                /****************** 原在80取权限 *******************/



                /****************** 现在新楼盘系统取权限 *******************/
                using (_Database db = new _Database("estate"))
                {
                    dt = zldc_GetAllPdmByRoleID_table(_Convert.ToInt(param.m_sRoleID, -2), "where IsAction=1 ", db);
                }

                if (dt != null && dt.Rows.Count > 0)
                    ZLDC.Common.Estate._Cache.SetCache(cachekey, dt, cachetime);
            }
            else
                dt = (DataTable)ZLDC.Common.Estate._Cache.GetCache(cachekey);

            if (dt.Rows.Count > 0)
            {
                DataRow[] dr = dt.Select("pdm='" + pdm.Trim() + "'");
                if (dr.Length > 0)
                    return true;
                else
                    return false;
            }
            else
            {
                return false;
            }

        }

        #region 获得权限的通用方法

        public static DataTable zldc_GetAllPdmByRoleID_table(int RoleID, string strWhere, _Database db)
        {
            List<SqlParameter> parms = new List<SqlParameter>();

            parms.Add(new SqlParameter("@RoleID", RoleID));
            parms.Add(new SqlParameter("@strWhere", strWhere));
            SqlParameter pRetval = new SqlParameter("@retval", SqlDbType.Int, 4);
            pRetval.Direction = ParameterDirection.ReturnValue;
            parms.Add(pRetval);

            DataTable dt = null;
            dt = db.GetDataTable("zldc_GetAllPdmByRoleID", parms);

            int retval = (pRetval.Value == System.DBNull.Value) ? 0 : Convert.ToInt32(pRetval.Value);

            return dt;
        }

        #endregion

        public static string getID(string name)
        {
            string[] names = name.Split(',');
            if (names.Length > 1)
            {
                if (names[0].Contains("["))
                {
                    string uid = names[0].Substring(names[0].LastIndexOf("[") + 1, names[0].Length - (names[0].LastIndexOf("[") + 1)).ToString().Trim();
                    return uid;
                }
            }
            return "";
        }

        public static string getName(string name)
        {
            if (name.Contains("["))
            {
                return name.Substring(0, name.LastIndexOf("[")).ToString().Trim();
            }
            return name;
        }

        public static bool getPopedom(string PdmPos, string pdm)
        {

            if (string.IsNullOrEmpty(PdmPos))
                return false;
            if (string.IsNullOrEmpty(pdm))
                return false;
            else
                return (pdm[Convert.ToInt16(PdmPos) - 1] == '1');
        }

        public static string getPdmNo(string pdm)
        {
            DataBase db = new DataBase();
            string returnStr = "";
            string commonStr = "select PdmPos from t_s_pdm where pdm = '" + pdm + "'";
            object obj = db.ScaleData(commonStr);
            if (DBNull.Value.Equals(obj) || null == obj)
            {
                returnStr = "";
            }
            else
            {
                returnStr = db.ScaleData(commonStr).ToString();
            }
            return returnStr;
        }

        public static string getRoleNo(string id)
        {
            DataBase db = new DataBase();
            string returnStr = "";
            string commonStr = "select r_id from t_s_allusr where id = '" + id + "'";
            object obj = db.ScaleData(commonStr);
            if (DBNull.Value.Equals(obj) || null == obj)
            {
                returnStr = "";
            }
            else
            {
                returnStr = db.ScaleData(commonStr).ToString();
            }
            return returnStr;
        }

        #endregion

        #region 获得部门的通用方法

        public static string getGetAllChildDeptAllUsers(string dept)
        {
            string strSql = @" declare @code nvarchar(500) 
                            declare @ID int 
                            set @ID='" + dept + "'";
            strSql += @"select @code=code from t_zlhq_t_s_alldept where ID =@ID
                            select @code=code from org_unit where ID in(select unitid from t_zldc_deptinfo where ID=@ID)
                            SELECT     h.ID, c.Code, c.EM_ID, c.Name, d.ID AS dept_id, d.Name AS deptName, CASE c.Sex WHEN 1 THEN '男' WHEN 2 THEN '女' END AS sex, 
                                      b.Name AS positionName, e.Status, c.BankAccountNum, CONVERT(varchar(10), f.ReJoinGroupDate, 23) AS ReJoinGroupDate, j.FCardID
                            FROM         dbo.ORG_Position_Employee AS a LEFT OUTER JOIN
                                      dbo.ORG_Position AS b ON a.PositionID = b.ID LEFT OUTER JOIN
                                      dbo.HM_Employees AS c ON c.EM_ID = a.EmID LEFT OUTER JOIN
                                      dbo.ORG_Unit AS d ON d.ID = b.UnitID LEFT OUTER JOIN
                                      dbo.HM_EM_EmpStatus_Code AS e ON e.ID = c.Status LEFT OUTER JOIN
                                      dbo.HM_EM_WorkInfo AS f ON f.EM_ID = c.EM_ID LEFT OUTER JOIN
                                      dbo.HR_ATS_BaseInfo AS j ON j.FEmpID = c.EM_ID INNER JOIN
                                      dbo.t_zldc_EmpInfo AS h ON h.UnitID = c.EM_ID
                            where d.code like @code+'%'";
            DataBaseAll db = new DataBaseAll("ZLDCHR");
            DataTable dt = db.SelectDataBaseAll(strSql).Tables[0];
            string strReturn = string.Empty;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i == 0)
                    strReturn = dt.Rows[i]["ID"].ToString();
                else
                    strReturn += "," + dt.Rows[i]["ID"].ToString();
            }
            return strReturn;
        }

        public static string getGetAllFatherDeptAllUsers(int deptid)
        {
            string strFathers = string.Empty;
            string strSql = @"declare @deptFullName nvarchar(500) ;
                            declare @strSql nvarchar(4000); 
                            declare @fgs nvarchar(40);
                            select  @deptFullName=''''+REPLACE(DeptFullName, '/',''',''')+'''', @fgs=fgs from t_zlhq_t_s_alldept where Id='" + deptid + "';";
            strSql += @"set @strSql='select * from t_zlhq_t_s_alldept where name in ('+@deptFullName+') and fgs='''+@fgs+''' and DltFlg=0 order by grade'
                            exec sp_executesql @strSql";
            using (Estate._Database db = new ZLDC.Common.Estate._Database("zlhq_user"))
            {
                DataSet dt1 = db.Query(strSql);
                if (dt1.Tables.Count > 0)
                {
                    for (int i = 0; i < dt1.Tables[0].Rows.Count; i++)
                    {
                        string strID = dt1.Tables[0].Rows[i]["ID"].ToString();
                        if (!string.IsNullOrEmpty(strID))
                        {
                            if (i == dt1.Tables[0].Rows.Count - 1)
                                strFathers += dt1.Tables[0].Rows[i]["ID"].ToString();
                            else
                                strFathers += dt1.Tables[0].Rows[i]["ID"].ToString() + ",";
                        }
                    }
                }
            }

            return strFathers;
        }

        public static DataTable getGetManagerUsers(string dept, string station)
        {
            string fatherdetps = getGetAllFatherDeptAllUsers(Convert.ToInt32(dept));
            string strSql = @" select * from kfb.t_s_allusr where t_id in (" + fatherdetps + ") and status<>'离职' and station <>'置业顾问'";

            if (!string.IsNullOrEmpty(station))
            {
                strSql += " and station='" + station + "'";
            }

            DataBaseAll db = new DataBaseAll("zlhq_user");
            DataTable dt = db.SelectDataBaseAll(strSql).Tables[0];
            return dt;
        }









        public static string getAllChildDept(string dept, string userid)
        {
            string strReturn = "";
            DataTable dt = null;

            using (Estate._Database db = new ZLDC.Common.Estate._Database("estate"))
            {
                try
                {
                    string sql = "select deptid from [f_GetAllChildDeptAll] (" + dept + ")";
                    DataSet ds = db.Query(sql);

                    if (ds != null && ds.Tables.Count > 0)
                        dt = ds.Tables[0];
                }
                catch { }
            }

            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string strID = dt.Rows[i]["deptid"].ToString();
                    if (!string.IsNullOrEmpty(strID))
                    {
                        if (i == dt.Rows.Count - 1)
                            strReturn += dt.Rows[i]["deptid"].ToString();
                        else
                            strReturn += dt.Rows[i]["deptid"].ToString() + ",";
                    }
                }
            }

            return strReturn;
        }

        public static string getFirstChildDept(string deptId, bool isContainsSelf)
        {
            string strReturn = string.Empty;

            if (deptId.Equals(""))
                return strReturn;

            string strSql = @"select * from t_zlhq_t_s_alldept where parent_id = " + deptId;
            if (isContainsSelf)
                strSql += " or ID = " + deptId;

            using (Estate._Database db = new ZLDC.Common.Estate._Database("zlhq_user"))
            {
                DataTable dt = db.Query(strSql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        string strID = dt.Rows[i]["ID"].ToString();
                        if (!string.IsNullOrEmpty(strID))
                        {
                            if (i == dt.Rows.Count - 1)
                                strReturn += dt.Rows[i]["ID"].ToString();
                            else
                                strReturn += dt.Rows[i]["ID"].ToString() + ",";
                        }
                    }
                }
            }

            return strReturn;
        }

        public static string GetManagePosDeptList(int userId)
        {
            string sRtn = string.Empty;

            string sSql = "select id from t_zlhq_t_s_alldept where pos_id in (select posid from t_s_ManagePos where uid = " + userId.ToString() + " and del = 0) and dltflg = 0;";
            using (Estate._Database db = new ZLDC.Common.Estate._Database("zlhq_user"))
            {
                DataTable dt = db.Query(sSql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        sRtn += dt.Rows[i]["id"].ToString().Trim() + ",";
                    }
                    sRtn = sRtn.TrimEnd(',');
                }
            }


            return sRtn;
        }

        public static int GetFatherYY_id(string deptid)
        {
            int parentId = 0;
            DataSet ds = null;
            string sql = "select  dbo.getFather_id(" + deptid + ")";

            using (_Database db = new _Database("estate"))
            {
                ds = db.Query(sql);
            }
            if (ds.Tables[0].Rows.Count > 0)
            {
                parentId = _Convert.ToInt(ds.Tables[0].Rows[0][0].ToString());
            }
            return parentId;

        }
        public static int GetFatherQY_id(string deptid)
        {
            int parentId = 0;
            DataSet ds = null;
            string sql = "select  dbo.getFatherQY_id(" + deptid + ")";
            using (_Database db = new _Database("estate"))
            {
                ds = db.Query(sql);
            }
            if (ds.Tables[0].Rows.Count > 0)
            {
                parentId = _Convert.ToInt(ds.Tables[0].Rows[0][0].ToString());
            }
            return parentId;

        }


        public static string GetBusinessDeptId()
        {
            string IdList = string.Empty;
            string sSql = " select id from t_zlhq_t_s_alldept where type='营业部' and dltflg = 0";
            using (Estate._Database db = new ZLDC.Common.Estate._Database("zlhq_user"))
            {
                DataTable dt = db.Query(sSql).Tables[0];
                if (dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        IdList += dt.Rows[i]["id"].ToString().Trim() + ",";
                    }
                    IdList = IdList.TrimEnd(',');
                }
            }

            return IdList;
        }

        #endregion
    }
}
